<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\ReceiveCouponCodeRequest;
use App\Models\CouponCode;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;

class CouponCodesController extends Controller
{
    public function show($code, Request $request)
    {
        if (!$record = CouponCode::query()->where('code', $code)->first()) {
            return $this->notFond('优惠券不存在');
        }

        $record->checkAvailable($request->user());

        return $this->success($record);
    }

    // 获取所有可以领取的优惠券
    public function index()
    {
        $data = CouponCode::query()->where("not_before", "<", Carbon::now())
            ->where("not_after", ">", Carbon::now())
            ->where("enabled", true)
            ->paginate(10);
        return $this->success($data);
    }

    // 领取优惠券
    public function receive(ReceiveCouponCodeRequest $request)
    {
        $request->user()->couponCodes()->attach($request->input('coupon_code_id'));
        return $this->message('领取成功');
    }

    // 获取所有优惠券
    public function indexUser(Request $request)
    {
        return $this->success($request->user()->couponCodes);
    }
}
